package net.csdn.business.common.utils;


import net.csdn.business.common.constant.AuthConstants;
import net.csdn.business.common.domain.vo.UserTokenVo;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wanghang
 * @date 2022/6/14 11:19
 */
public class AuthUtil {

    /**
     * 获取 idToken
     *
     * @param request
     * @return
     */
    public static String getIdToken(HttpServletRequest request) {
        //优先从cookie获取
        String accessToken = getCookieValue(request, AuthConstants.ATOMGIT_ID_TOKEN);
        if (StringUtils.isNotBlank(accessToken)) {
            return accessToken;
        }
        return getHeaderValue(request, AuthConstants.TOKEN_KEY);
    }

    /**
     * 获取 accessToken
     *
     * @param request
     * @return
     */
    public static String getAccessToken(HttpServletRequest request) {
        //优先从cookie获取
        String accessToken = getCookieValue(request, AuthConstants.ATOMGIT_ACCESS_TOKEN);
        if (StringUtils.isNotBlank(accessToken)) {
            return accessToken;
        }
        return getHeaderValue(request, AuthConstants.TOKEN_KEY);
    }


    /**
     * 获取 mfa二次验证的批次号
     *
     * @param request
     * @return
     */
    public static String getMfaVerifyId(HttpServletRequest request) {
        //优先从cookie获取
        String accessToken = getCookieValue(request, AuthConstants.ATOMGIT_MFA_VERIFY_ID);
        if (StringUtils.isNotBlank(accessToken)) {
            return accessToken;
        }
        return getHeaderValue(request, AuthConstants.ATOMGIT_MFA_VERIFY_ID);
    }

    /**
     * 当前是否为模拟用户状态
     *
     * @param request
     * @return
     */
    public static boolean isSimulate(HttpServletRequest request) {
        String simulateSymbol = getCookieValue(request, AuthConstants.ATOMGIT_SIMULATE_SYMBOL);
        if (AuthConstants.SIMULATE_SYMBOL_VALUE.equals(simulateSymbol)) {
            return true;
        }
        return false;
    }

    // /**
    //  * 模拟状态下的管理员用户ID
    //  *
    //  * @param request
    //  * @return
    //  */
    // public static String getSimulateAdminUserId(HttpServletRequest request) {
    //     return getCookieValue(request, AuthConstants.ATOMGIT_ADMIN_USER_ID);
    // }
    //
    // /**
    //  * 模拟状态下的管理员用户名
    //  *
    //  * @param request
    //  * @return
    //  */
    // public static String getSimulateAdminUserName(HttpServletRequest request) {
    //     return getCookieValue(request, AuthConstants.ATOMGIT_ADMIN_USER_NAME);
    // }

    /**
     * 获取 refreshToken
     *
     * @param request
     * @return
     */
    public static String getRefreshToken(HttpServletRequest request) {
        //优先从cookie获取
        String accessToken = getCookieValue(request, AuthConstants.ATOMGIT_REFRESH_TOKEN);
        if (StringUtils.isNotBlank(accessToken)) {
            return accessToken;
        }
        return getHeaderValue(request, AuthConstants.ATOMGIT_REFRESH_TOKEN);
    }

    /**
     * 从header中获取数据
     *
     * @param request
     * @return
     */
    public static String getHeaderValue(HttpServletRequest request, String key) {
        return request.getHeader(key);
    }

    /**
     * 从cookie中获取数据
     *
     * @param key
     * @param request
     * @return
     */
    public static String getCookieValue(HttpServletRequest request, String key) {
        try {
            Cookie[] cookies = request.getCookies();
            if (cookies == null) {
                return null;
            }
            for (Cookie cookie : cookies) {
                if (key.equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        } catch (Exception e) {
            System.out.println("获取cookie失败:" + e.getMessage());
        }
        return null;
    }

    /**
     * 回写用户cookie
     *
     * @param userToken
     * @param response
     * @param cookieDomain
     */
    public static void setCookie(UserTokenVo userToken, HttpServletResponse response, String cookieDomain) {
        removeUserCookie(response, cookieDomain);
        addCookie(response, AuthConstants.ATOMGIT_ID_TOKEN, userToken.getId_token(), cookieDomain);
        addCookie(response, AuthConstants.ATOMGIT_ACCESS_TOKEN, userToken.getAccess_token(), cookieDomain);
        addCookie(response, AuthConstants.ATOMGIT_REFRESH_TOKEN, userToken.getRefresh_token(), cookieDomain);
        addCookie(response, AuthConstants.ATOMGIT_EXPIRES_IN, String.valueOf(userToken.getExpires_in()), cookieDomain);
        addCookie(response, AuthConstants.ATOMGIT_EXPIRES_AT, String.valueOf(userToken.getExpires_at()), cookieDomain);
        addCookie(response, AuthConstants.DEFAULT_LANG, userToken.getDefaultLang(), cookieDomain,false);
    }

    /**
     * 清空用户cookie
     *
     * @param response
     * @param cookieDomain
     */
    public static void removeUserCookie(HttpServletResponse response, String cookieDomain) {
        if (response == null) {
            return;
        }
        delCookie(response, AuthConstants.ATOMGIT_ID_TOKEN, cookieDomain);
        delCookie(response, AuthConstants.ATOMGIT_ACCESS_TOKEN, cookieDomain);
        delCookie(response, AuthConstants.ATOMGIT_REFRESH_TOKEN, cookieDomain);
        delCookie(response, AuthConstants.ATOMGIT_EXPIRES_IN, cookieDomain);
        delCookie(response, AuthConstants.ATOMGIT_EXPIRES_AT, cookieDomain);
        delCookie(response, AuthConstants.DEFAULT_LANG, cookieDomain);
        delCookie(response, AuthConstants.ATOMGIT_SIMULATE_SYMBOL, cookieDomain);
        delCookie(response, AuthConstants.ATOMGIT_ADMIN_USER_ID, cookieDomain);
        delCookie(response, AuthConstants.ATOMGIT_ADMIN_USER_NAME, cookieDomain);
    }

    public static void addCookie(HttpServletResponse response, String key, String value, String cookieDomain) {
        Cookie cookie = new Cookie(key, value);
        cookie.setHttpOnly(true);
        cookie.setPath("/");
        cookie.setMaxAge(AuthConstants.COOKIE_MAX_AGE);
        cookie.setDomain(cookieDomain);
        cookie.setSecure(true);
        response.addCookie(cookie);
    }

    public static void addCookie(HttpServletResponse response, String key, String value, String cookieDomain,boolean httpOnly) {
        Cookie cookie = new Cookie(key, value);
        cookie.setHttpOnly(httpOnly);
        cookie.setPath("/");
        cookie.setMaxAge(AuthConstants.COOKIE_MAX_AGE);
        cookie.setDomain(cookieDomain);
        cookie.setSecure(true);
        response.addCookie(cookie);
    }

    public static void delCookie(HttpServletResponse response, String key, String cookieDomain) {
        Cookie cookie = new Cookie(key, "");
        cookie.setHttpOnly(true);
        cookie.setPath("/");
        cookie.setDomain(cookieDomain);
        cookie.setMaxAge(0);
        cookie.setSecure(true);
        response.addCookie(cookie);
    }

    /**
     * 模拟用户cookie
     *
     * @param response
     * @param cookieDomain
     * @param token         被模拟用户token
     * @param adminUserId   管理员用户ID
     * @param adminUsername 管理员用户名
     */
    public static void addSimulateCookie(HttpServletResponse response, String cookieDomain, String token, String adminUserId, String adminUsername) {
        addCookie(response, AuthConstants.ATOMGIT_ACCESS_TOKEN, token, cookieDomain);
        addCookie(response, AuthConstants.ATOMGIT_SIMULATE_SYMBOL, AuthConstants.SIMULATE_SYMBOL_VALUE, cookieDomain);
        addCookie(response, AuthConstants.ATOMGIT_ADMIN_USER_ID, adminUserId, cookieDomain);
        addCookie(response, AuthConstants.ATOMGIT_ADMIN_USER_NAME, adminUsername, cookieDomain);
    }

    /**
     * 取消用户模拟cookie
     *
     * @param response
     * @param cookieDomain
     */
    public static void removeSimulateCookie(HttpServletResponse response, String cookieDomain) {
        delCookie(response, AuthConstants.ATOMGIT_SIMULATE_SYMBOL, cookieDomain);
        delCookie(response, AuthConstants.ATOMGIT_ADMIN_USER_ID, cookieDomain);
        delCookie(response, AuthConstants.ATOMGIT_ADMIN_USER_NAME, cookieDomain);
    }

}
